package com.batis.session;


import com.batis.config.Configuration;
import com.batis.config.MapperStatement;
import com.batis.exe.DefaultExecutor;
import com.batis.exe.Executor;
import com.batis.exe.ProxyMapper;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.List;
import java.util.Objects;

/**
 * 1,把客户端的请求转给executor
 * 2,生成mapper接口的实现类
 *
 * @author carter
 * create time    2018-08-17
 */
public class DefaultSqlSession implements SqlSession {

    private Configuration configuration;

    private Executor executor;


    public DefaultSqlSession(Configuration configuration) {
        this.configuration = configuration;
        executor = new DefaultExecutor(configuration);
    }


    @Override
    public <T> T selectOne(String statment, Object param) {

        List<T> list = this.selectList(statment,param);

        if (Objects.isNull(list) || list.isEmpty())
        {
            return null;
        }

        if (list.size() == 1)
        {
            return list.get(0);
        }else
        {
            throw  new RuntimeException("many result ,need one ");
        }

    }

    @Override
    public <T> List<T> selectList(String statment, Object param) {

        MapperStatement mapperStatement = configuration.getStatementMap().get(statment);
        return executor.query(mapperStatement,param);
    }

    @Override
    public <T> T getMapper(Class<T> type) {
        Object o = Proxy.newProxyInstance(type.getClassLoader(), new Class[]{type}, new ProxyMapper(this));
        return (T) o;
    }
}
